/**
 * Copyright 2010 Adam Ruggles.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package saig.engine.controllers;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import saig.engine.Context;
import saig.engine.Environment;


/**
 * A Human player controller.
 * @author Adam
 * @version $Id$
 * 
 * Created on Jun 5, 2010 at 10:14:07 PM 
 */
public class HumanController implements Controller, KeyListener {
	/**
	 * The key state.
	 */
	private final boolean[] keyState = new boolean[Context.NUMBER_OF_KEYS];
	/**
	 * {@inheritDoc}
	 * @see saig.engine.controllers.Controller#getInput(Environment.core.GameState)
	 */
	@Override
	public boolean[] getInput(final Environment environment) {
		return keyState;
	}

	/**
	 * {@inheritDoc}
	 * @see saig.engine.controllers.Controller#getName()
	 */
	@Override
	public String getName() {
		return "Human Player";
	}

	/**
	 * {@inheritDoc}
	 * @see saig.engine.controllers.Controller#reset()
	 */
	@Override
	public void reset() {
		for (int i = 0; i < Context.NUMBER_OF_KEYS; i++) {
			keyState[i] = false;
		}
	}
	/**
	 * {@inheritDoc}
	 * @see java.awt.event.KeyListener#keyPressed(java.awt.event.KeyEvent)
	 */
	@Override
	public void keyPressed(KeyEvent e) {
		setKeyState(e, true);
	}
	/**
	 * {@inheritDoc}
	 * @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent)
	 */
	@Override
	public void keyReleased(KeyEvent e) {
		setKeyState(e, false);
	}
	/**
	 * Sets the keystate based on the key event and value.
	 * @param e The KeyEvent.
	 * @param value The value to set.
	 */
	private void setKeyState(KeyEvent e, boolean value) {
		final int keyCode = e.getKeyCode();
		switch(keyCode) {
		case KeyEvent.VK_RIGHT:
			keyState[Context.KEY_RIGHT] = value;
			break;
		case KeyEvent.VK_LEFT:
			keyState[Context.KEY_LEFT] = value;
			break;
		case KeyEvent.VK_UP:
			keyState[Context.KEY_A] = value;
			break;
		case KeyEvent.VK_DOWN:
			keyState[Context.KEY_DOWN] = value;
			break;
		case KeyEvent.VK_SPACE:
			keyState[Context.KEY_B] = value;
			break;
		}
	}
	/**
	 * {@inheritDoc}
	 * @see java.awt.event.KeyListener#keyTyped(java.awt.event.KeyEvent)
	 */
	@Override
	public void keyTyped(KeyEvent e) { }

}
